﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity.Utility;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Configuration;

namespace Artech.EnterLibExt.ExceptionHandling
{
    public class ExceptionFilterTable
    {
        public IEnumerable<ExceptionFilterTableEntry> FilterEntries{get; private set;}

        public ExceptionFilterTable(IEnumerable<ExceptionFilterTableEntry> filterTableEntries)
        {
            Guard.ArgumentNotNull(filterTableEntries, "filterTableEntries");
            this.FilterEntries = filterTableEntries;
        }

        public IEnumerable<IExceptionHandler> GetExceptionHandlers(Exception ex)
        {
            Guard.ArgumentNotNull(ex, "ex");
            var highPriorityEntryGroup = (from filterTableEntry in this.FilterEntries
                                            where filterTableEntry.Filter.Match(ex)
                                            group filterTableEntry by filterTableEntry.Priority into g
                                            orderby g.Key descending
                                            select g).FirstOrDefault();
            if (null == highPriorityEntryGroup)
            {
                return new List<IExceptionHandler>();
            }
            if (highPriorityEntryGroup.Count() > 1)
            {
                throw new ConfigurationErrorsException("error...");
            }
            return highPriorityEntryGroup.AsEnumerable().First().ExceptionHandlers;           
        }
    }
}
